import { createStore } from 'vuex'
import api from "@/api/index"

export default createStore({
  state: {
    isLogin:null,
    info:null, 
    storeList:null  // 收藏列表
  },
  mutations: {
    changeIsLogin(state,bool){
      state.isLogin = bool
    },
    changeInfo(state,info){
      state.info = info
    },
    queryStoreList(state,payload){
      state.storeList = payload;
    },
    removeStoreList(state,id){ // id 9478926
      if(!state.storeList) return;
      // 根据id移除个你收藏的新闻
      state.storeList = state.storeList.filter(item=>{
        return +item.id != +id
      })
    }
  },
  actions: {
    // 检查是否登录
    async changeIsLoginAsync({commit}){
      let {code,data} = await api.checkLogin();
      if(code !== 0){
        // 表示没有登录
        commit("changeIsLogin",false)
        return
      }
      commit("changeIsLogin",true)
      commit("changeInfo",data)
      return true
    },
    // 获取用户信息
    async changeInfoAsync({commit}){
      let {code,data} = await api.userInfo();
      if(code !== 0) return null;
      commit("changeInfo",data)
      return data
    },
    // 获取收藏列表
    async queryStoreListAsync({commit}){
      let {code,data} = await api.storeList();
      if(code !== 0) data = [];
      commit("queryStoreList",data)
      return data;
    }
  }
})
